package sf.core;

import sf.database.dao.DBContext;
import sf.database.meta.MetaHolder;
import sf.r2dbc.dao.R2dbcTemplate;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 在每个需要延迟加载的对象中存放一个。
 * 用于记录已经加载的字段和尚未加载的字段。
 */
class R2dbcLazyLoadContext implements ILazyLoadContext {
    private R2dbcTemplate client;
    private DBContext context;
    private Set<String> hasLoadFields = new HashSet<>(4);

    public R2dbcLazyLoadContext(R2dbcTemplate client, DBContext context) {
        this.client = client;
        this.context = context;
    }

    @Override
    public boolean needLoad(String fieldname) {
        return !hasLoadFields.contains(fieldname);
    }

    @Override
    public boolean process(DBObject dataObject, String fieldname) {
        Map<String, DBCascadeField> cascadeFields = MetaHolder.getMeta(dataObject.getClass()).getCascadeFields();
        if (!cascadeFields.containsKey(fieldname)) {//不是级联字段,跳过
            return false;
        }
        R2dbcLazyLoadUtils.loadCascadeObject(client, context, dataObject, fieldname);
        markProcessed(fieldname);//在对象直接使用字段反射注入的时候,不会调用beforeSet方法
        return hasLoadFields.size() == cascadeFields.size();
    }


    /**
     * 在级联对象set的时候会调用 beforeSet方法
     * @param field
     */
    @Override
    public void markProcessed(String field) {
        hasLoadFields.add(field);
    }

    @Override
    public LazyLoadProcessor getProcessor() {
        return null;
    }
}
